/**
 * 生产计划 生产订单
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">生产计划</el-breadcrumb-item>
      <el-breadcrumb-item>生产订单</el-breadcrumb-item>
    </el-breadcrumb>
    
    <!-- 根据订单编号搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.order_num" placeholder="输入订单号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>

    <!-- 生产订单列表-->
    <el-table size="small"
     :data="tableData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
      <el-table-column align="center" prop="id" label="序号" width="50">
      </el-table-column>
      <el-table-column  prop="order_status" align="center" label="订单状态" width="80">
      </el-table-column>
      <el-table-column  prop="order_priority" align="center" label="优先级" width="50">
      </el-table-column>
      <!-- <el-table-column  prop="order_progress"  align="center" label="订单进度" width="80" >
        <el-progress :text-inside="true" :stroke-width="26" :percentage="100"></el-progress>
      </el-table-column> -->
      <el-table-column  prop="order_num" align="center" label="订单号" width="100">
      </el-table-column>
      <el-table-column  prop="order_type" align="center" label="订单类型" width="80">
      </el-table-column>
      <el-table-column  prop="order_nature" align="center" label="订单性质" width="80">
      </el-table-column>
      <el-table-column  prop="order_client" align="center" label="订单客户" width="80">
      </el-table-column>
      <el-table-column  prop="order_contract" align="center" label="合同编号" width="100">
      </el-table-column>
      <el-table-column  prop="total_money" align="center" label="订单总价" width="80">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="500">
        <template slot-scope="scope">
          <el-button size="mini" @click="detailOrder(scope.row)">详情</el-button>
          <el-button size="mini" @click="positionOrder(scope.row)">下发</el-button>
          <el-button size="mini" type="danger" @click="handleExitO(scope.row)">撤回</el-button>
          <el-button size="mini" type="danger" @click="termination(scope.row)">终止</el-button>
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteOrder(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather" align="center"/>

    <!-- 订单详情页面 -->
    <el-dialog :title = "title" :visible.sync = "detail_item" width="80%" @click="closeDialog">
      <DetailOrder :detailorder = "detailorder"/>
    </el-dialog>
    
    <!-- 编辑界面 -->
     <el-dialog :title="title" :visible.sync="editFormVisible" width="55%" @click="closeDialog">
      
    <el-form
    :inline = "true"
    label-width="100px"   
    :model="editForm"
    ref="editForm">
       
    <el-form-item 
      label="生产订单编码" prop="order_num">
    <el-input 
      size="small" 
      placeholder="请输入编码"
      v-model="editForm.order_num" auto-complete="off"
      :disabled="true"
      >
    </el-input>
    </el-form-item>
            
    <el-form-item 
      label="订单类型" 
      prop="order_type">
    <el-input 
      size="small" 
      placeholder="请输入订单类型"
      v-model="editForm.order_type"
      :disabled = "true"
    >
    </el-input>
    </el-form-item>
            
    <el-form-item 
      label="订单客户" prop="order_client">
    <el-select v-model="editForm.order_client" @change="selectChanged">
            <el-option v-for="item in order_clientData" :key="item.name" :value="item.name" :label="item.name"/>
    </el-select>
    </el-form-item>

    <el-form-item 
      label="产品编码" prop="material_code" >
      <el-select v-model="editForm.material_code" @focus="productDetail">
            <el-option v-for="item in material_codeData" :key="item.material_code" :value="item.material_code" :label="item.material_code"/>
      </el-select>
      <!-- <el-input
      size="small" 
      placeholder="请输入产品名称"
      v-model="editForm.material_code"
      :disabled = "false"
    >
    </el-input> -->
    </el-form-item>

    <el-form-item 
      label="产品名称" prop="product_name">
    <el-input
      size="small" 
      placeholder="请输入产品名称"
      v-model="editForm.product_name"
      :disabled = "true"
    >
    </el-input>
    </el-form-item>

    <el-form-item 
      label="产品类型" prop="product_type">
    <el-input 
      size="small" 
      placeholder="请输入产品类型"
      v-model="editForm.product_type"
      :disabled = "true"
    >
    </el-input>
    </el-form-item>

    <el-form-item 
      label="交货日期" prop="delivery_date">
      <el-date-picker
        v-model="editForm.delivery_date"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="请输入交货日期">
      </el-date-picker>

    </el-form-item>

    <el-form-item 
      label="计划开始时间" prop="start_time">
    <el-date-picker
        v-model="editForm.start_time"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="请输入计划开始时间">
      </el-date-picker>
    </el-form-item>

    <el-form-item 
      label="计划完成时间" prop="finish_time">
    <el-date-picker
        v-model="editForm.finish_time"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="请输入计划完成时间">
      </el-date-picker>
    </el-form-item>
         
    <el-form-item 
      label="订单优先级" 
      prop="order_priority">
      
    <el-input 
      size="small" 
      placeholder="请输入订单优先级"
      v-model="editForm.order_priority"
      :disabled = "true"
    >
    </el-input>
    </el-form-item>

    <el-form-item 
      label="订单性质" prop="order_nature">
    <el-input 
      size="small" 
      placeholder="请输入订单性质"
      v-model="editForm.order_nature"
      :disabled="true"
    >
    </el-input>
    </el-form-item>

    <el-form-item 
      label="合同编号" prop="order_contract">
    <el-input 
      size="small" 
      placeholder="请输入合同编号"
      v-model="editForm.order_contract"
      auto-complete="off"
      :disabled="true"
    >
    </el-input>
    </el-form-item>

    <el-form-item 
      label="订单数量" 
      prop="order_account">
    <el-input 
      size="small" 
      placeholder="请输入订单数量"
      v-model="editForm.order_account"
    >
    </el-input>
    </el-form-item>

  </el-form>     
    <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm()">保存</el-button>
      </div>
    </el-dialog>

    <!-- 显示产品表 产品名称，产品类型 -->
    <el-dialog :title="title" :visible.sync="material_codeVisible" width="40%"  @click="closeDialog">
      <el-table
    :data="productDetailData"
    height="250"
    border
    style="width: 100%"
    highlight-current-row @current-change="handleCurrentChange">
    <el-table-column
      prop="material_code"
      label="产品编码"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="产品名称"
      width="180">
    </el-table-column>
    <el-table-column
      prop="production_type"
      label="产品类型"
      width="160">
    </el-table-column>
  </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closematerial_code">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitmaterial_code()">保存</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>

import { deptList, deptSave, deptDelete } from '../../api/userMG'
import Pagination from '../../components/Pagination'
import DetailOrder from '../../components/DetailOrder.vue'


export default {
  data() {
    return {
      //时间选择框
      pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
      title: "",// 弹窗标题
      loading: false, // 整个页面显示加载
      editFormVisible: false, // 控制编辑页面显示与隐藏
      detail_item:false,// 控制详情页面显示与编辑
      material_codeVisible:false,// 产品信息弹窗
      // 添加、编辑页面的数据
      editForm: {
        id:"",
        order_num:"",
        order_client:"",
        product_name:"",
        order_status:"",
        material_code:"",
        delivery_date:"",
        finish_time:"",
        order_priority:"",
        order_nature:"",
        order_contract:"",
        order_account:"",
        product_type:"",
        order_type:"",
        start_time:"",
        total_money:""
      },
      // rules表单验证
      rules: {
        deptName: [
          { required: true, message: '请输入订单编号', trigger: 'blur' }
        ],
      },
      // 详情页面数据
      detailorder:[{
        order_num :'',
        order_client:'',
        material_code:'',
        production_type:'',
        name:'',
        order_account:'',
        price:'',
        total_money:'',
        token: localStorage.getItem('logintoken')
      },
      ],
      // 搜索框中的数据
      formInline: {
        page: 1,
        limit: 10,
        order_num:'',
        token: localStorage.getItem('logintoken')
      },
      // 选中行数
      seletedata: {
        id: '',
        token: localStorage.getItem('logintoken')
      },
      // 页面表单显示的数据
      tableData:[],
      userparm: [], //搜索权限
      order_clientData:[],//客户姓名列表
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      // 表单数据
      listData: [],
      // 产品编码数据
      material_codeData: [],
      // 产品信息数据
      productDetailData: [],
    }
  },
  // 注册组件
  components: {
    Pagination,
    DetailOrder, 
  },

  //钩子函数 在组件第一次渲染的时候才执行
  created() {
    // this.getdata(this.formInline)
    this.getdata();
    
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取下拉框中值
    selectChanged(val){
      console.log(val)
      
      this.$axios.get('/api/productionPlan/merchants/' + encodeURI(encodeURI(val))).then(
        res => {
          console.log(res.data.data)
          this.editForm.order_priority = res.data.data
        }
      ).catch()
    },
    
    // 获取客户姓名
    getorder_clientData(){
      this.$axios.get('/api/productionPlan/merchants').then(res => {
      this.order_clientData = res.data.data
      }).catch()
    },
    // 根据产品编码获取产品数据
    getmaterial_codeData(){
        this.$axios.get('/api/production/production').then(res => {
              this.productDetailData=res.data.data
        }).catch()
    
    },
    // 产品信息弹窗方法
    productDetail(){
      this.material_codeVisible = true;
      this.getmaterial_codeData();
    },
    // 弹出框选中值
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    // 产品弹出框取消
    closematerial_code(){
      this.material_codeVisible = false;
    },
    // 产品弹出框保存
    submitmaterial_code(){
      this.editForm.product_name = this.currentRow.name;
      this.editForm.product_type = this.currentRow.production_type;
      this.editForm.material_code = this.currentRow.material_code;
      this.material_codeVisible = false;
    },
    // 获取订单列表
    getdata(parameter) {

      this.loading = true
      this.$axios.get('/api/productionPlan/order/' + this.pageparm.currentPage + '/' + this.pageparm.pageSize)
        .then(res => {
          this.loading = false             
         if(res.data.code == 200){      
            this.tableData = res.data.data.list
            this.pageparm.total = res.data.data.total;
            let data1 = res.data.data.list;
            for(const i in data1){
              if(data1[i].order_status == 1){
                data1[i].order_status = '已下发'
              }
              if(data1[i].order_status == 0){
                data1[i].order_status = '未下发'
              }
              if(data1[i].order_status == 2){
                data1[i].order_status = '已发货'
              }
              if(data1[i].order_status == 3){
                data1[i].order_status = '正在结算中'
              }
            }
             //分页赋值
            // this.pageparm.currentPage = res.formInline.page
            // this.pageparm.pageSize = res.formInline.limit
          }else{
            this.$message({
              type:'info',
              message:res.data.message
            })
          }
        })
        .catch(err => {
          this.$message.error("菜单加载失败，请重试！")
        })

    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage
      this.pageparm.pageSize = parm.pageSize
      // this.getdata(this.formInline)
      this.getdata();
    },
    // 搜索事件
    search() {
      if(this.formInline.order_num != null){
        this.$axios.get("/api/productionPlan/order/" + this.formInline.order_num)
        .then(res => {
          this.loading = false
          console.log(res.data.data)

            if(res.data.code == 200 && res.data != null){
              this.$message.success("订单查找成功！")
              this.tableData = res.data.data
            }else{
             this.$message({
                type:"info",
                message:res.data.message
              })
            }
        })
      }else{
        this.$message.info("请输入订单编号！");
        this.getdata(this.tableData);
      }
    },
    // 显示编辑界面
    handleEdit(row){
      this.editFormVisible = true;
      this.getmaterial_codeData();
      this.getorder_clientData();
      
      if (row != undefined && row != "undefined") {
        this.title = "修改";
        //填充数据
        this.editForm.order_num = row.order_num;
        this.editForm.order_type = row.order_type;
        this.editForm.order_client = row.order_client;
        this.editForm.product_name = row.product_name;
        this.editForm.material_code = row.material_code;
        this.editForm.delivery_date = row.delivery_date;
        this.editForm.finish_time = row.finish_time;
        this.editForm.order_priority = row.order_priority;
        this.editForm.order_nature = row.order_nature;
        this.editForm.order_contract = row.order_contract;
        this.editForm.product_type = row.product_type;
        this.editForm.order_account = row.order_account;
        this.editForm.start_time = row.start_time;
        
      } else {
        this.title = "添加";
        this.editForm.order_num = "SDDC"+this.uuid(3,10);
        this.editForm.order_status = "0";
        this.editForm.order_type = "普通订单";
        this.editForm.order_progress = "0%"
        this.editForm.order_client = "";
        this.editForm.product_name = "";
        this.editForm.material_code = "";
        this.editForm.delivery_date = "";
        this.editForm.finish_time = "";
        this.editForm.order_priority = "一级";
        this.editForm.order_nature = "销售";
        this.editForm.order_contract = "HOEB" + this.uuid(6,10);
        this.editForm.product_type = "";
        this.editForm.order_account = "";
        this.editForm.start_time = "";
      }
    },
    // 编辑、增加页面保存方法
    submitForm() {
     // 判断是修改还是新增
        if (this.title == "添加") {
            // 新增
            this.$axios.post("/api/productionPlan/order", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error("保存失败，请稍后再试！");
            });
        } else {
          
            // 修改
            this.$axios.put("/api/productionPlan/order", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error("保存失败，请稍后再试！");
            });
        }
    },
    // 删除选中的订单
    deleteOrder(row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.delete("api/productionPlan/order/"+row.order_num)
          .then((res) => {
            if(res.data.code == 200){
              this.$message({
                type:"success",
                message:"已删除！",
              });
              this.getdata();
            }else{
              this.$message({
                type:"info",
                message:res.data.message
              });
            }
          })
          .catch((err) => {
            this.$message.error("删除失败，请稍后再试！")
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });

    },
    // 详情页面显示方法
    detailOrder(row){
      //表名
      this.title = "订单详情"
      //页面显示
      this.detail_item = true
      //页面发送请求
      this.$axios.get("api/productionPlan/detailOrders/"+ row.order_num)
      .then(res=>{
        console.log(res)
        this.detailorder=res.data.data
        })
      .catch(err => {
        this.loading = false
        this.$message.error("订单详情页面加载失败，请稍后再试!")
      })
    },
    // 下发订单方法 成功
    positionOrder(row){
      this.$confirm('确定下发订单吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.put("api/productionPlan/positionOrders/"+row.order_num)
          .then((res) => {
            if(res.data.code == 200){
              this.$message({
                type:"success",
                message:"已下发！",
              });
              this.getdata();
            }else{
              this.$message({
                type:"info",
                message:res.data.message
              });
            }
          })
          .catch((err) => {
            this.$message.error("下发失败，请稍后再试！")
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下发',
          });
        });
    },
    // 撤回订单方法
    handleExitO(row){
      this.$confirm('确定撤回订单吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.put("api/productionPlan/handleExitOrders/"+row.order_num)
          .then((res) => {
            if(res.data.code == 200){
              this.$message({
                type:"success",
                message:"已撤回！",
              });
              this.getdata();
            }else{
              this.$message({
                type:"info",
                message:res.data.message
              });
            }
          })
          .catch((err) => {
            this.$message.error("下发撤回，请稍后再试！")
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消撤回',
          });
        });
    },
    // 终止订单方法
    termination(row){
      this.$confirm('确定终止订单吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.put("api/productionPlan/terminationOrders/"+row.order_num)
          .then((res) => {
            if(res.data.code == 200){
              this.$message({
                type:"success",
                message:"已终止！",
              });
              this.getdata();
            }else{
              this.$message({
                type:"info",
                message:res.data.message
              });
            }
          })
          .catch((err) => {
            this.$message.error("终止失败，请稍后再试！")
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消终止',
          });
        });
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },
    // uuid的算法方法
    uuid(len, radix) {
      var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
      var uuid = [], i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
      } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join('');
    },

  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 
 